package com.joseph.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeoutException;

import javax.annotation.Resource;

import org.apache.lucene.index.FieldInvertState;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.github.xsonorg.XSON;
import com.joseph.base.BaseController;
import com.joseph.base.BaseDto;
import com.joseph.model.Product;
import com.joseph.model.User;
import com.joseph.service.ProductService;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

/**
 * @description 
 * @author Joseph_Mok
 * @date 2016年1月25日上午11:40:44
 */
@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations="/conf/spring-context.xml")  
public class T extends BaseController {

	@Resource
	private ProductService productService;
	
	public static void main(String[] args) throws IOException, SolrServerException {
		
	}
	
	@Test
	public void test() throws IOException, SolrServerException {
		HttpSolrServer server = new HttpSolrServer(SOLR_URL);
	    server.setMaxRetries(1);
	    server.setConnectionTimeout(5000); // 5 seconds to establish TCP
	    // server.setRequestWriter(new BinaryRequestWriter());

	    SolrQuery query = new SolrQuery();
	    query.set("wt", "json");
	    query.setQuery("keyword:卫衣");
	    query.setStart(0);
	    query.setRows(20);
	    //query.setFacet(true);
	    //query.addFacetField("author_s"); 面包屑

	    SolrDocumentList results = server.query(query).getResults();
	    server.shutdown();
	    StringBuilder sb = new StringBuilder();
	    sb.append(results.get(0).getFieldValue("id"));
	    for (int i = 1; i < results.size(); i++) {
	    	sb.append(",").append(results.get(i).getFieldValue("id"));
	    }
	    System.out.println(sb.toString());
	    BaseDto dto = new BaseDto();
	    dto.put("ids", sb.toString());
	    List <Product> list = productService.getByIds(dto);
	    System.out.println(list);
	}
	
	@Test
	public void mq_send() throws IOException, TimeoutException {
		ConnectionFactory connectionFactory = new ConnectionFactory();
		//factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");
		connectionFactory.setHost(MQ_URL);
		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();
		 //指定一个队列  
        channel.queueDeclare(MQ_QUEUE_NAME_PRODUCT, false, false, false, null);  
        //发送的消息  
        Product product = new Product();
        product.setId("889");
        product.setCn("我的卫衣joseph");
        product.setImageURL("http://www.baidu.com");
        product.setPrice("120.00");
        
        //往队列中发出一条消息  
        channel.basicPublish("", MQ_QUEUE_NAME_PRODUCT, null, XSON.write(product)); 
        
        System.out.println(XSON.write(product));
        //关闭频道和连接  
        channel.close();  
        connection.close();  
	}
	
	@Test
	public void mq_recv() throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, SolrServerException {
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost(MQ_URL);
		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();
        channel.queueDeclare(MQ_QUEUE_NAME_PRODUCT, false, false, false, null);  
        
        QueueingConsumer consumer = new QueueingConsumer(channel);  
        //指定消费队列  
        channel.basicConsume(MQ_QUEUE_NAME_PRODUCT, true, consumer);  
        //nextDelivery是一个阻塞方法（内部实现其实是阻塞队列的take方法） 
        
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
        Product product = XSON.parse(delivery.getBody());  
        
        HttpSolrServer server = new HttpSolrServer(SOLR_URL);
        SolrInputDocument sd = new SolrInputDocument();
        sd.addField("cn", product.getCn());
        sd.addField("id", product.getId());
        //sd.addField("price", product.getPrice());
        server.add(sd);
        server.commit();
        channel.close();
        connection.close();
	}
	
	@Test
	public void seri() throws IOException {
		User user = new User();
		OutputStream os = new FileOutputStream("D:/user.ser");
		ObjectOutputStream oos = new ObjectOutputStream(os);
		//ObjectInputStream ois = new ObjectInputStream(in)
		oos.writeObject(user);
		oos.close();
	}
	
	@Test
	
	
	public void deseri() throws IOException, ClassNotFoundException {
		InputStream is = new FileInputStream("D:/user.ser");
		ObjectInputStream oos = new ObjectInputStream(is);
		User u = (User) oos.readObject();
		System.out.println(u.getNickname());
		System.out.println(u.getPassword());
		oos.close();
	}
	
	@Test
	public void codeMap() {
		//ApplicationContext context = new ClassPathXmlApplicationContext("/conf/spring-context.xml");  
		//CodeMap codeMap = (CodeMap) context.getBean("codeMap");  
		System.out.println(Double.valueOf(new java.text.DecimalFormat("#0.00").format(12.30d + 13.31d - 21.21d - 321.21d - 12.31d)));
	}
	
	@Test
	public void jdbc() {
		java.sql.Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
	}
	
	@Test
	public void classLoader() throws ClassNotFoundException, MalformedURLException {
		File file = new File("D:/");
		URL [] uris = {file.toURL()};
		MyClassLoader loader = new MyClassLoader(uris);
		Class <Tank> tank = loader.findClass("T");
		System.out.println(tank.getClassLoader());
	}
}
